import React, { useState, useEffect } from 'react';
import { Drawer, message, Tag, Space } from 'antd';
import { connect, Dispatch } from 'umi';
import { PARAM_LIST,
  PARAM_ADD,
  PARAM_UPDATE,
  PARAM_DELETE, UPDATE_STATE } from '@/actions/param';
import ProCard from '@ant-design/pro-card';
import ProDescriptions, { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import {PageContainer } from '@ant-design/pro-layout';
import AGrid, { AGridButtonCallBackModel } from '@/components/SelfComp/AGrid';
import { ConnectState } from '@/models/connect';
import ParamQueryForm from './components/ParamQueryForm';
import AddParamModal from './components/AddParamModal';
import UpdateParamModal from './components/UpdateParamModal';
import { ParamItem } from './data';

interface ParamListProps {
  dispatch: Dispatch;
  paramList: ParamItem[],
  total: number,
  loading: boolean;
  pageSize: number;
  addLoading: boolean;
  updateLoading: boolean;
}

const EMPTY_PARAM: ParamItem = {
  paramId: '',
  paramName: '',
  paramKey: '',
  paramValue: '',
  paramValueDesc: '',
  paramStates: ''
}

/**
 * 参数列表管理
 * @param props 属性
 * @returns 参数列表
 */
const ParamList: React.FC<ParamListProps> = (props) => {
  const code = 'param-list';
  const { paramList, loading, total, addLoading, updateLoading } = props;
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [row, setRow] = useState<ParamItem>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<ParamItem[]>([]);
  const [queryParam, setQueryParam] = useState<ParamItem>(EMPTY_PARAM);
  const [pageSize, setPageSize] = useState<number>(10);
  const [paramFormData, setParamFormData] = useState<ParamItem>(EMPTY_PARAM);
  const rowKey = (record: ParamItem) => {
    return record.paramId;
  }
  const pkField = 'paramId';
  const columns = [
    {
      title: '参数名称',
      dataIndex: 'paramName',
      width: 250,
      render: (text: string, record: ParamItem, index: number) => {
        return <a onClick={() => setRow(record)}>{text}</a>;
      },
    },
    {
      title: '参数键名',
      dataIndex: 'paramKey',
      width: 300,
    },
    {
      title: '参数键值',
      dataIndex: 'paramValue',
      width: 300,
    },
    {
      title: '参数键值描述',
      dataIndex: 'paramValueDesc',
    }
  ];

  useEffect(() => {
    console.info('ParamList.useEffect');
    fetchAllParam(1, 10, queryParam);
    return () => {
      const { dispatch } = props;
      dispatch(UPDATE_STATE({
        rows: [],
        total: 0
      }));
    }
  }, []);

  /**
   * 查询满足条件的数据字典
   */
  const handleQuery = (record: ParamItem) => {
    console.info('ParamList.handleQuery');
    console.info(record);
    const queryParam = {
      ...record
    };
    // 查询条件保存起来，方便点击页码时使用
    // setState回调方法，保证先更新state
    fetchAllParam(1, pageSize, queryParam);
  }

  const handleReset = () => {
    // 是否清空表格
  }

  /**
   * 分页查询系统参数信息
   * @param {*} pageNum 页码
   * @param {*} pageSize 每页记录条数
   */
  const fetchAllParam = (pageNum: number, pageSize: number, queryParam: ParamItem) => {
    const { dispatch } = props;
    dispatch(PARAM_LIST({
      ...queryParam,
      pageSize,
      pageNum
    }));
  }

  /**
   * 删除用户，暂时只支持单笔删除
   * @param userId 用户id
   */
  const deleteParams = async (keys: React.Key[]) => {
    const { dispatch } = props;
    const res = await dispatch(PARAM_DELETE(keys));
    if (res) {
      dispatch(PARAM_LIST({
        ...queryParam,
        pageSize,
        pageNum: 1,
      }));
    }
  }

  /**
   * 处理按钮点击回调事件
   * @param {*} payload 数据包
   */
  const handleBtnCallBack = (callBackModel: AGridButtonCallBackModel<ParamItem>) => {
    console.log('handleBtnCallBack');
    console.log(callBackModel);
    // btn 按钮
    // keys 表格勾选数组
    const { btn } = callBackModel;
    const { alias } = btn;
    // 新增
    if (alias === 'add') {
      handleAddModalVisible(true);
      return;
    }
    // 修改
    if (alias === 'edit') {
      const { rows } = callBackModel;
      setParamFormData(rows[0]);
      handleUpdateModalVisible(true);
      return;
    }
    // 删除
    if (alias === 'delete') {
      const { keys } = callBackModel;
      // 调用删除服务，删除勾选数据
      deleteParams(keys);
      return;
    }
  }

  /**
   * 表格勾选回调函数
   * @param {*} rows 表格选中数据集合
   */
  const onSelectRow = (keys: React.Key[], rows: ParamItem[]) => {
    setSelectedRowKeys(keys);
    setSelectedRows(rows);
  };

  /**
   * 页码改变的回调，参数是改变后的页码及每页条数
   * @param page 改变后的页码，上送服务器端
   * @param pageSize 每页数据条数
   */
  const onPageNumAndSizeChange = (page: number, pageSize: number) => {
    console.log(page, pageSize);
    setPageSize(pageSize);
    fetchAllParam(page, pageSize, queryParam);
  };

  const handleAddModal = async (record: ParamItem) => {
    console.log(record);
    const { dispatch } = props;
    console.info(dispatch);
    const res = await dispatch(PARAM_ADD(record));
    console.info(res);
    if (res) {
      handleAddModalVisible(false);
      fetchAllParam(1, pageSize, queryParam);
    }
  }

  const handleAddModalCancel = () => {
    handleAddModalVisible(false);
  };

  /**
   * 更新面板的确定事件
   * @param {*} record 更新表单
   */
  const handleUpdateModal = async (record: ParamItem) => {
    console.log('handleUpdateModalOk');
    console.log(record);
    console.info(paramFormData);
    const { dispatch } = props;
    const res = await dispatch(PARAM_UPDATE(record));
    console.info(res);
    if (res) {
      handleUpdateModalVisible(false);
      setParamFormData(EMPTY_PARAM);
      fetchAllParam(1, pageSize, queryParam);
    }
  }

  const handleUpdateModalCancel = () => {
    handleUpdateModalVisible(false);
    setParamFormData(EMPTY_PARAM);
  };

  return (
    <PageContainer>
      <Space direction='vertical' size='middle' style={{ display: 'flex' }}>
        <ProCard title="查询条件" headerBordered>
          <ParamQueryForm
            colon={false}
            loading={loading}
            onSubmit={(record) => {
              setQueryParam(record);
              handleQuery(record);
            }}
            onReset={handleReset}
          />
        </ProCard>
        <ProCard>
          <AGrid
            code={code}
            btnCallBack={handleBtnCallBack}
            columns={columns}
            rowKey={rowKey}
            pkField={pkField}
            dataSource={paramList}
            loading={loading}
            total={total}
            onSelectRow={onSelectRow}
            onPageNumAndSizeChange={onPageNumAndSizeChange}
          />
        </ProCard>
      </Space>
      {
        !addModalVisible ? null :
        <AddParamModal
          colon={false}
          modalTitle='新增参数'
          modalWidth={1000}
          modalVisible={addModalVisible}
          loading={addLoading}
          onHandlerOK={handleAddModal}
          onHandlerCancel={handleAddModalCancel}
        />
      }
      {
        !updateModalVisible ? null :
        <UpdateParamModal
          colon={false}
          modalTitle=''
          modalWidth={1000}
          modalVisible={updateModalVisible}
          flag='edit'
          loading={updateLoading}
          formData={paramFormData}
          onHandlerOK={handleUpdateModal}
          onHandlerCancel={handleUpdateModalCancel}
        />
      }
      <Drawer
        width={600}
        open={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.paramId && (
          <ProDescriptions<ParamItem>
            column={2}
            title={row?.paramName}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.paramId,
            }}
            columns={columns as ProDescriptionsItemProps<ParamItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};


export default connect((state: ConnectState) => ({
  paramList: state.params.rows,
  total: state.params.total,
  loading: state.loading.effects['params/fetchAllParam'],
  addLoading: state.loading.effects['params/addParam'],
  updateLoading: state.loading.effects['params/updateParam']
}))(ParamList);